package main

import (
	"bufio"
	"bytes"
	"fmt"
	"github.com/ipfs/go-cid"
	"io/ioutil"
	"net/http"
	"os"
	"strings"

	shell "github.com/ipfs/go-ipfs-api"
)

func main() {
	// Where your local node is running on localhost:5001
	//url:="localhost:5001"
	//url:="149.129.75.92:5001"
	url:="localhost:5002"
	sh := shell.NewShell(url)


	// 保存文本
	cid, err := sh.Add(strings.NewReader("hello world!"))
	if err != nil {
		fmt.Fprintf(os.Stderr, "error: %s", err)
		os.Exit(1)
	}
	fmt.Printf("added %s", cid)


	rc,err:=sh.Cat(cid)
	if err!=nil{
		fmt.Fprintf(os.Stderr, "cat error: %s", err)
		os.Exit(1)
	}

	buf := new(bytes.Buffer)
	buf.ReadFrom(rc)
	fmt.Printf("文本内容: %s",buf.String())



	//保存文件

	filedata,err:=ioutil.ReadFile("d:\\findata-spider.log")
	if err!=nil{
		fmt.Fprintf(os.Stderr, "error: %s", err)
		os.Exit(1)
	}
	cid2, err := sh.Add(bytes.NewBuffer(filedata))

	if err != nil {
		fmt.Fprintf(os.Stderr, "error: %s", err)
		os.Exit(1)
	}
	fmt.Printf("added %s\n", cid2)

    //保存图片  使用百度图片
	img_url:="https://www.baidu.com/img/bd_logo1.png?where=super"

	resp,err:=http.Get(img_url)
	if err != nil {
		fmt.Fprintf(os.Stderr, "error: %s\n", err)
		os.Exit(1)
	}
	defer resp.Body.Close()
	r:=bufio.NewReaderSize(resp.Body, 32 * 1024)
	cid3, err := sh.Add(r)
	if err != nil {
		fmt.Fprintf(os.Stderr, "error: %s", err)
		os.Exit(1)
	}
	fmt.Printf("added %s\n", cid3)


  fmt.Printf("打印 cid: ")
	gencid()
}

const File  = "./READ.ME"


func gencid(){
	p := cid.Prefix{
		Version:  1,
		Codec:    0x70,  // prtobuf
		MhType:   0x12,  // sha2-256
		MhLength: -1,
	}


	data,err:=ioutil.ReadFile(File)
	if err != nil {
		panic(err)
	}

	fcid,err:=p.Sum(data)
	if err != nil{
		panic(err)
	}

	fmt.Println(fcid)



}
